package com.sailfish.springbootdemo.service.db1;

import com.alibaba.fastjson.JSONObject;
import com.sailfish.springbootdemo.common.DB1EmailTemplates;
import com.sailfish.springbootdemo.configs.UserHeaderHolder;
import com.sailfish.springbootdemo.dao.db1.AuditHistoryDao;
import com.sailfish.springbootdemo.dao.db1.PcbaCompanyDao;
import com.sailfish.springbootdemo.dao.db1.RoadmapCmStatusDao;
import com.sailfish.springbootdemo.dao.db4.UserDao;
import com.sailfish.springbootdemo.pojo.Result;
import com.sailfish.springbootdemo.pojo.db1.AuditHistory;
import com.sailfish.springbootdemo.pojo.db1.PcbaCompany;
import com.sailfish.springbootdemo.pojo.db1.RoadmapCmStatus;
import com.sailfish.springbootdemo.pojo.db2.MailAddress;
import com.sailfish.springbootdemo.pojo.db4.Operate;
import com.sailfish.springbootdemo.pojo.db4.User;
import com.sailfish.springbootdemo.service.db2.ThirdApiService;
import com.sailfish.springbootdemo.service.db4.OperateService;
import com.sailfish.springbootdemo.utils.CommonUtils;
import com.sailfish.springbootdemo.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class RoadmapCmStatusServiceImpl implements RoadmapCmStatusService {

    @Autowired
    private RoadmapCmStatusDao roadmapCmStatusDao;

    @Autowired
    private AuditHistoryDao auditHistoryDao;

    @Value("${personal.config.env}")
    private String env;

    @Autowired
    private ThirdApiService thirdApiService;

    @Autowired
    private UserDao userDao;

    @Autowired
    private PcbaCompanyDao pcbaCompanyDao;

    @Qualifier("MysqlTransactionManager1")
    @Autowired
    private DataSourceTransactionManager transactionManager1;

    @Autowired
    private OperateService operateService;

    private String operateSmallType = "Roadmap CM 审核";

    @Override
    public Result getRoadmapCmStatusByCompanyAndVersion(Integer pcbaCompanyId, Integer versionY, String versionN) {
        try {
            if (pcbaCompanyId == null || "".equals(pcbaCompanyId.toString())) {
                return ResultUtil.error(500, "缺少参数pcbaCompanyId", "Miss Param pcbaCompanyId", null);
            }
            if (versionY == null || "".equals(versionY.toString())) {
                return ResultUtil.error(500, "缺少参数versionY", "Miss Param versionY", null);
            }
            if (versionN == null || "".equals(versionN)) {
                return ResultUtil.error(500, "缺少参数versionN", "Miss Param versionN", null);
            }
            return ResultUtil.success(roadmapCmStatusDao.getRoadmapCmStatusByCompanyAndVersion(pcbaCompanyId, versionY, versionN));
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @Override
    public Result updateRoadmapCmStatus(RoadmapCmStatus roadmapCmStatus) {
        try {
            if (roadmapCmStatus == null) {
                return ResultUtil.error(500, "缺少参数roadmapCmStatus", "Miss Param roadmapCmStatus", null);
            }
            if (roadmapCmStatus.getRoadmapCmStatusId() == null || "".equals(roadmapCmStatus.getRoadmapCmStatusId().toString())) {
                return ResultUtil.error(500, "缺少参数roadmapCmStatusId", "Miss Param roadmapCmStatusId", null);
            }
            String userId = UserHeaderHolder.getUserId();
            Date d = new Date();
            RoadmapCmStatus oldRoadmapCmStatus = roadmapCmStatusDao.getRoadmapCmStatusById(roadmapCmStatus.getRoadmapCmStatusId());

            roadmapCmStatus.setUpdateTime(d);
            roadmapCmStatus.setSubmitter(Integer.parseInt(userId));
            Integer integer = roadmapCmStatusDao.updateRoadmapCmStatus(roadmapCmStatus);
            if (integer > 0) {

                // 操作日志
                operateService.addOperate(new Operate(1, Integer.parseInt(userId), operateSmallType, 3, 1, new Date(), JSONObject.toJSONString(oldRoadmapCmStatus), JSONObject.toJSONString(roadmapCmStatus)));

                if (roadmapCmStatus.getStatus() == 1 || roadmapCmStatus.getStatus() == 2 || roadmapCmStatus.getStatus() == 3) {
                    // 添加 审核记录
                    AuditHistory addAuditHistory = new AuditHistory();
                    addAuditHistory.setAuditType(7);
                    addAuditHistory.setCreateTime(d);
                    addAuditHistory.setSubmitUserId(null);
                    addAuditHistory.setAuditUserId(Integer.parseInt(userId));
                    addAuditHistory.setAuditStatus(roadmapCmStatus.getStatus());
                    addAuditHistory.setAuditNotes(roadmapCmStatus.getNotes());
                    addAuditHistory.setRelatedId(roadmapCmStatus.getRoadmapCmStatusId());
                    auditHistoryDao.addAuditHistory(addAuditHistory);
                } else {
                    // 添加 审核记录
                    AuditHistory addAuditHistory = new AuditHistory();
                    addAuditHistory.setAuditType(7);
                    addAuditHistory.setCreateTime(d);
                    addAuditHistory.setSubmitUserId(Integer.parseInt(userId));
                    addAuditHistory.setAuditUserId(null);
                    addAuditHistory.setAuditStatus(roadmapCmStatus.getStatus());
                    addAuditHistory.setAuditNotes(null);
                    addAuditHistory.setRelatedId(roadmapCmStatus.getRoadmapCmStatusId());
                    auditHistoryDao.addAuditHistory(addAuditHistory);
                }

                // 发送邮件通知
                try {
                    List<User> userList = new ArrayList<>();
                    Integer pcbaCompanyId = oldRoadmapCmStatus.getPcbaCompanyId();
                    if (pcbaCompanyId != null) {
                        PcbaCompany pcbaCompany = pcbaCompanyDao.getPcbaCompanyById(pcbaCompanyId);
                        if (pcbaCompany != null) {
                            String emailOwners5 = pcbaCompany.getEmailOwners5();
                            if (emailOwners5 != null && !"".equals(emailOwners5)) {
                                String[] split = emailOwners5.split(",");
                                for (String s : split) {
                                    if (s.contains("/")) {
                                        String[] strings = s.split("\\/");
                                        if (strings.length == 2) {
                                            String domainAccount = strings[1];
                                            if (domainAccount != null && !"".equals(domainAccount)) {
                                                User u = userDao.getUserInfoByDomainAccount(domainAccount);
                                                if (u != null) {
                                                    userList.add(u);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    List<MailAddress> mailAddressList = new ArrayList<>();
                    for (User user : userList) {
                        if(user.getEmail().contains(",")){
                            String[] emailsArr = user.getEmail().split(",");
                            for (String email : emailsArr) {
                                MailAddress mailAddress = new MailAddress();
                                mailAddress.setMailAddress(email);
                                mailAddress.setType(0);
                                mailAddressList.add(mailAddress);
                            }
                        }else{
                            MailAddress mailAddress = new MailAddress();
                            mailAddress.setMailAddress(user.getEmail());
                            mailAddress.setType(0);
                            mailAddressList.add(mailAddress);
                        }
                    }
                    if (mailAddressList.size() > 0) {
                        if (roadmapCmStatus.getStatus() == 1) {
                            Result result = thirdApiService.sendMail("", DB1EmailTemplates.ROADMAP_TITLE_OK, DB1EmailTemplates.ROADMAP_MAIL_CONTENT_TITLE_OK,
                                    DB1EmailTemplates.ROADMAP_MAIL_CONTENT_OK, "10086", mailAddressList, null, null, null, null, 2, null);
                            if (result.getCode() == 200) {
                                System.out.println(CommonUtils.formatCurrentTime() + "==========================================");
                                System.out.println("roadmap审核结果邮件,发送成功");
                            } else {
                                System.out.println(CommonUtils.formatCurrentTime() + "==========================================");
                                System.out.println("roadmap审核结果邮件,发送失败:" + result.getMsgCn());
                            }
                        } else if (roadmapCmStatus.getStatus() == 2) {
                            Result result = thirdApiService.sendMail("", DB1EmailTemplates.ROADMAP_TITLE_NO, DB1EmailTemplates.ROADMAP_MAIL_CONTENT_TITLE_NO,
                                    DB1EmailTemplates.ROADMAP_MAIL_CONTENT_NO, "10086", mailAddressList, null, null, null, null, 2, null);
                            if (result.getCode() == 200) {
                                System.out.println(CommonUtils.formatCurrentTime() + "==========================================");
                                System.out.println("roadmap审核结果邮件,发送成功");
                            } else {
                                System.out.println(CommonUtils.formatCurrentTime() + "==========================================");
                                System.out.println("roadmap审核结果邮件,发送失败:" + result.getMsgCn());
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println(CommonUtils.formatCurrentTime() + "==========================================");
                    System.out.println("roadmap审核结果邮件发送失败");
                }

                return ResultUtil.success(null);
            }
            return ResultUtil.error(500, "操作失败", "Operate Fail", null);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }
}
